<template>
  <div>
    <!-- 添加模块 -->
    <div style="margin-bottom: 10px;">
      <el-button type="success" @click="handleAdd()">新增员工</el-button>
    </div>

    <!-- 新增员工弹窗 -->
    <el-dialog title="新增员工" v-model="showAddForm" width="30%">
      <el-form :model="staffFrom" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="staffFrom.staffName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="staffFrom.staffContact" autocomplete="off" />
        </el-form-item>
        <el-form-item label="方向">
          <el-select v-model="staffFrom.majorId" placeholder="请选择方向">
            <el-option v-for="(majorName, majorId) in majorMap" :key="majorId" :label="majorName" :value="majorId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddForm = false">取 消</el-button>
          <el-button type="primary" @click="handleAddStaff()">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改员工弹窗 -->
    <el-dialog title="修改员工" v-model="showEditForm" width="30%">
      <el-form :model="staffFrom" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="staffFrom.staffName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系方式" prop="staffContact">
          <el-input v-model="staffFrom.staffContact" autocomplete="off" />
        </el-form-item>
     
          <el-form-item label="方向">
            <el-select v-model="staffFrom.majorId" placeholder="请选择方向">
              <el-option v-for="(majorName, majorId) in majorMap" :key="majorId" :label="majorName" :value="majorId" />
            </el-select>
          </el-form-item>


      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditForm = false">取 消</el-button>
          <el-button type="primary" @click="handleEditStaff()">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 员工列表 -->
    <el-table :data="tableData" style="width: 100%" border :row-class-name="tableRowClassName">
      <el-table-column prop="staffId" label="员工ID" />
      <el-table-column prop="staffName" label="员工姓名" />
      <el-table-column prop="staffContact" label="联系方式" width="150" />
      <el-table-column prop="staffCreated" label="创建时间" width="180">
        <template #default="scope">{{ formatTime(scope.row.staffCreated) }}</template>
      </el-table-column>
      <el-table-column prop="majorId" label="方向ID">
        <template #default="scope">{{ majorMap[scope.row.majorId] }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="hasDeleteButton" type="danger" @click="handleDelete(scope.row.staffId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <!-- layout:里面的值的顺序就是页面显示顺序 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        :size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
  
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElMessage, ElMessageBox } from 'element-plus';
import { addStaffApi, updateStaffApi, deleteStaffApi, getStaffListApi, queryContactApi } from '@/api/api';

//分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(10)
const size = ref('default')

// 员工名称
const searchName = ref('');

// 表格数据
const tableData = ref([]);

// 员工列表
const staffFrom = ref({
  staffId: null,
  staffName: '',
  staffContact: '',
  majorId: null,
});
// 方向映射
const majorMap = ref<any>([]);
//修改的方向映射，分开是为了不直接影响table的数据
const majorMapForEdit = ref<any>([]);

// 是否显示添加表单
const showAddForm = ref(false);
// 是否显示修改表单
const showEditForm = ref(false);

// 手机号
const editPhone = ref('');

// 打开新增员工弹窗
const handleAdd = () => {
  showAddForm.value = true;
  staffFrom.value = {
    staffId: null,
    staffName: '',
    staffContact: '',
    majorId: null,
  }
};

// 打开修改员工弹窗
const handleEdit = (row: any) => {
  showEditForm.value = true;
  staffFrom.value = { ...row }; // 确保 staffFrom 是独立的副本
  staffFrom.value.majorId = majorMap.value[row.majorId];
  majorMapForEdit.value = { ...majorMap.value }; // 确保 majorMapForEdit 是独立的副本
  editPhone.value = row.staffContact;
};


// 员工列表
const staffList = async () => {
  const response = await getStaffListApi({ page: currentPage.value, size: pageSize.value, name: searchName.value });
  console.log('获取员工列表返回结果', response);
  if (response.code === 200) {
    tableData.value = response.data.pageVo.list;
    total.value = response.data.pageVo.total;

    //majorId 和 majorName 的映射
    majorMap.value = {};
    response.data.list.forEach((item: any) => {
      if (item.majorId) {
        majorMap.value[item.majorId] = item.majorName;
      }
    });

  } else {
    ElMessage.error('获取员工列表失败');
  }
}

// 处理每页显示条数变化的事件
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  staffList();
};
// 处理当前页码变化的事件
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  staffList();
};

// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}


// 提交新增员工
async function handleAddStaff() {
  // 表单校验
  // 姓名不能为空
  if (!staffFrom.value.staffName) {
    ElMessage.error('姓名不能为空');
    return;
  }
  //手机号格式
  if (!staffFrom.value.staffContact) {
    ElMessage.error('联系方式不能为空');
    return;
  }
  //手机号格式
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(staffFrom.value.staffContact)) {
    ElMessage.error('联系方式格式不正确');
    return;
  }
  const res = await queryContactApi({ staffContact: staffFrom.value.staffContact });
  if (res.code === 200 && res.data) {
    ElMessage.error('联系方式已存在');
    return;
  }

  // 方向不能为空
  if (!staffFrom.value.majorId) {
    ElMessage.error('方向不能为空');
    return;
  }

  // 调用新增接口
  const response = await addStaffApi(staffFrom.value);
  if (response.code === 200) {
    ElMessage.success('新增成功');
    showAddForm.value = false;
    staffList();
  } else {
    ElMessage.error(response.msg);
  }
}

// 提交修改员工
async function handleEditStaff() {

  // 表单校验
  // 姓名不能为空
  if (!staffFrom.value.staffName) {
    ElMessage.error('姓名不能为空');
    return;
  }
  //手机号格式
  if (!staffFrom.value.staffContact) {
    ElMessage.error('联系方式不能为空');
    return;
  }
  //手机号格式
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(staffFrom.value.staffContact)) {
    ElMessage.error('联系方式格式不正确');
    return;
  }
  if (staffFrom.value.staffContact !== editPhone.value) {
    const res = await queryContactApi({ staffContact: staffFrom.value.staffContact });
    if (res.code === 200 && res.data) {
      ElMessage.error('联系方式已存在');
      return;
    }
  }

  // 方向不能为空
  if (!staffFrom.value.majorId) {
    ElMessage.error('方向不能为空');
    return;
  }


  // 表单校验
  const response = await updateStaffApi(staffFrom.value);
  if (response.code === 200) {
    ElMessage.success('修改成功');
    showEditForm.value = false;
    staffList();
  } else {
    ElMessage.error(response.msg);
  }
}

// 删除员工
const handleDelete = async (id: number) => {
  ElMessageBox.confirm(
    '确认删除该员工?',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await deleteStaffApi(id);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        staffList();
      } else {
        ElMessage.error(response.msg);
      }
    } catch (error) {
      ElMessage.error('操作失败');
    }
  }).catch(() => {
    ElMessage.info('已取消');
  });
}


// 按钮权限列表
const buttonList = ref([]);
const hasDeleteButton = computed(() => {
  return buttonList.value.some(button => button === 'delete');
});


// 页面加载完后，加载默认数据
onMounted(() => {
  staffList();
  const storedButtons = localStorage.getItem('buttonList');
  if (storedButtons) {
    buttonList.value = JSON.parse(storedButtons);
  }
});
// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  row
  if (rowIndex % 2 === 0) {
    return 'success-row'
  }
  return ''
}

</script>
  
<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>